import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/api' : (process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080'),
  timeout: 600000, // 10分钟超时，因为3D模型生成可能较长
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token等
    const token = localStorage.getItem('authToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response

  },
  (error) => {
    // 统一错误处理
    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 400:
          throw new Error(data.message || '请求参数错误')
        case 401:
          throw new Error('未授权，请重新登录')
        case 403:
          throw new Error('权限不足')
        case 404:
          throw new Error('请求的资源不存在')
        case 429:
          throw new Error('请求过于频繁，请稍后再试')
        case 500:
          throw new Error('服务器内部错误')
        default:
          throw new Error(data.message || '请求失败')
      }
    } else if (error.request) {
      throw new Error('网络连接失败，请检查网络')
    } else {
      throw new Error('请求配置错误')
    }
  }
)

// 用户认证API接口
export const authAPI = {
  // 用户登录
  async login(credentials) {
    try {
      const response = await api.post('/users/login', {
        username: credentials.username,
        password: credentials.password
      })
      const result = response.data || {}
      const payload = result.data || {}
      if (payload.token) {
        localStorage.setItem('authToken', payload.token)
        localStorage.setItem('userInfo', JSON.stringify(payload))
      }
      return { success: true, data: payload }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 用户注册
  async register(userData) {
    try {
      const response = await api.post('/users/register', {
        username: userData.username,
        password: userData.password,
        email: userData.email,
        phone: userData.phone
      })
      
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 用户登出
  async logout() {
    try {
      await api.post('/users/logout')
      
      // 清除本地存储
      localStorage.removeItem('authToken')
      localStorage.removeItem('userInfo')
      
      return {
        success: true
      }
    } catch (error) {
      // 即使服务器登出失败，也要清除本地存储
      localStorage.removeItem('authToken')
      localStorage.removeItem('userInfo')
      
      return {
        success: true
      }
    }
  },

  // 获取当前用户信息
  async getCurrentUser() {
    try {
      const response = await api.get('/users/me')
      const result = response.data || {}
      return { success: true, data: result.data || null }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  async changePassword(payload) {
    try {
      const response = await api.put('/users/password', payload)
      const result = response.data || {}
      return { success: true, data: result }
    } catch (error) {
      return { success: false, error: error.message }
    }
  },

  // 检查用户名是否可用
  async checkUsername(username) {
    try {
      const response = await api.get(`/users/check-username/${username}`)
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }
}

// API接口定义
export const modelAPI = {
  // 异步生成3D模型（文字描述）
  async generateModelAsync(requestData) {
    try {
      const response = await api.post('/image3d/generateAsync', {
        prompt: requestData.prompt,
        resultFormat: requestData.resultFormat,
        enablePBR: requestData.enablePBR
      })
      
      const result = response.data || {}
      return {
        success: true,
        data: result.data || null
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 异步生成3D模型（图片上传）
  async generateFromImageAsync(requestData) {
    try {
      const formData = new FormData()
      formData.append('request', new Blob([JSON.stringify({
        enablePBR: requestData.enablePBR,
        resultFormat: requestData.resultFormat
      })], { type: 'application/json' }))
      formData.append('imageFile', requestData.imageFile)
      
      const response = await api.post('/image3d/generateFromImageAsync', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      const result = response.data || {}
      return {
        success: true,
        data: result.data || null
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 查询任务状态
  async getTaskStatus(taskId) {
    try {
      const response = await api.get(`/image3d/status/${taskId}`)
      const result = response.data || {}
      return {
        success: true,
        data: result.data || null
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 获取用户历史记录
  async getHistory() {
    try {
      const response = await api.get('/image3d/history')
      const result = response.data || {}
      return {
        success: true,
        data: result.data || []
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 生成3D模型（文字描述）- 保留同步接口
  async generateModel(requestData) {
    try {
      const response = await api.post('/image3d/getImageOfPrompt', {
        prompt: requestData.prompt,
        resultFormat: requestData.resultFormat,
        enablePBR: requestData.enablePBR,
        timestamp: Date.now()
      })
      
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 生成3D模型（图片上传）
  async generateModelFromImage(requestData) {
    try {
      // 构建JSON数据
      const jsonData = {
        resultFormat: requestData.resultFormat,
        enablePBR: requestData.enablePBR,
        timestamp: Date.now()
      }
      
      // 创建FormData，包含文件和JSON数据
      const formData = new FormData()
      formData.append('imageFile', requestData.imageFile)
      formData.append('image3DDto', new Blob([JSON.stringify(jsonData)], { type: 'application/json' }))
      
      // 发送请求
      const response = await axios.post(
        `${process.env.NODE_ENV === 'development' ? '/api' : (process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080')}/image3d/getImageOfImage`,
        formData,
        {
          headers: {
            // 不设置Content-Type，让浏览器自动设置multipart/form-data的boundary
          },
          responseType: 'blob',
          timeout: 600000
        }
      )
      
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 检查生成状态
  async checkStatus(taskId) {
    try {
      const response = await api.get(`/models/status/${taskId}`)
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 获取模型列表
  async getModelList(page = 1, limit = 10) {
    try {
      const response = await api.get('/models', {
        params: { page, limit }
      })
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 删除模型
  async deleteModel(modelId) {
    try {
      const response = await api.delete(`/models/${modelId}`)
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 下载模型
  async downloadModel(modelId) {
    try {
      const response = await api.get(`/models/${modelId}/download`, {
        responseType: 'blob'
      })
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }
}

// 模拟认证API（用于开发测试）
export const mockAuthAPI = {
  async login(credentials) {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟登录验证
    if (credentials.username === 'admin' && credentials.password === '123456') {
      return {
        success: true,
        data: {
          user: {
            id: 1,
            username: 'admin',
            email: 'admin@example.com',
            phone: '13800138000',
            createdAt: new Date().toISOString()
          },
          token: 'mock-jwt-token-' + Date.now()
        }
      }
    } else {
      return {
        success: false,
        error: '用户名或密码错误'
      }
    }
  },

  async register(userData) {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟注册
    return {
      success: true,
      data: {
        message: '注册成功',
        user: {
          id: Math.floor(Math.random() * 1000),
          username: userData.username,
          email: userData.email,
          phone: userData.phone,
          createdAt: new Date().toISOString()
        }
      }
    }
  },

  async logout() {
    // 模拟登出
    await new Promise(resolve => setTimeout(resolve, 500))
    return { success: true }
  },

  async getCurrentUser() {
    // 模拟获取当前用户信息
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const token = localStorage.getItem('authToken')
    if (token && token.startsWith('mock-jwt-token-')) {
      return {
        success: true,
        data: {
          id: 1,
          username: 'admin',
          email: 'admin@example.com',
          phone: '13800138000',
          createdAt: new Date().toISOString()
        }
      }
    } else {
      return {
        success: false,
        error: 'Token无效'
      }
    }
  },

  async checkUsername(username) {
    // 模拟用户名检查
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟一些已存在的用户名
    const existingUsernames = ['admin', 'test', 'user', 'demo']
    
    return {
      success: true,
      data: {
        available: !existingUsernames.includes(username.toLowerCase())
      }
    }
  }
}

// 模拟API（用于开发测试）
export const mockAPI = {
  async generateModel() {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟同步成功响应：code为"200"表示成功，data为模型URL
    return {
      success: true,
      data: {
        code: '200',
        msg: '成功',
        data: 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Avocado/glTF-Binary/Avocado.glb'
      }
    }
  },

  async checkStatus(taskId) {
    // 模拟状态检查
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟不同的状态
    const random = Math.random()
    if (random < 0.3) {
      return {
        success: true,
        data: {
          taskId,
          status: 'processing',
          progress: Math.floor(Math.random() * 80) + 10,
          message: '正在生成模型...'
        }
      }
    } else if (random < 0.8) {
      return {
        success: true,
        data: {
          taskId,
          status: 'completed',
          progress: 100,
          modelUrl: 'https://threejs.org/examples/models/gltf/Parrot/Parrot.glb', // 使用示例模型
          message: '模型生成完成'
        }
      }
    } else {
      return {
        success: true,
        data: {
          taskId,
          status: 'failed',
          progress: 0,
          message: '模型生成失败'
        }
      }
    }
  }
}

// 根据环境变量选择是否使用Mock
const useMock = String(process.env.VUE_APP_USE_MOCK || '').toLowerCase() === 'true'
export const currentAPI = useMock ? mockAPI : modelAPI
export const currentAuthAPI = useMock ? mockAuthAPI : authAPI

export default api
